<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Di\DollarPhraseMapper;

use Selibra\Di\DI;
use Selibra\Tools\Console;

class DollarPhrase
{

    /**
     * 解析字符串
     * @param ?string $key
     * @return mixed
     */
    public static function resolve(?string $key): mixed
    {
        if (empty($key) || !str_starts_with($key, '$')) {
            return $key;
        }
        $keyArray = explode('.', $key);
        $namespace = DollarPhraseMapperCollect::getMapper($keyArray[0]);
        if (is_null($namespace)) {
            return $key;
        }
        // 从映射中读取
        /** @var DollarPhraseInterface $mapper */
        $mapper = DI::getObjectContext($namespace);
        unset($keyArray[0]);
        return $mapper->getValue(implode('.', $keyArray));
    }

}
